import axios from "axios";
import s from "@/libs/store";
const wx = window.wx;

const baseUrl =
  process.env.NODE_ENV === "development"
    ? "http://47.102.99.194:9001/"
    : "//app.lianlianhongbao.com/";
class Share {
  constructor() {}
  init(options) {
    this._location = location.href;
    this._basePath = this.getBasePath();
    this._shareConfig = {
      title: options.title || document.title,
      desc: options.desc || this._location,
      link: options.link || this._location,
      imgUrl: this._basePath + options.imgUrl,
      trigger: function(res) {
        // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
        //alert('用户点击发送给朋友');
      },
      success: function(res) {
        //alert('已分享');
        options.successHandler && options.successHandler();
      },
      cancel: function(res) {
        //alert('已取消');
      },
      fail: function(res) {
        //alert(JSON.stringify(res));
      }
    };
    this._debug = options.debug || false;
    if (
      /micromessenger/i.test(navigator.userAgent) &&
      s.localStorage.get("token")
    ) {
      this.CreateAjax();
      this.wxReady();
      this.wxError();
      this.addImg();
    }
  }
  CreateAjax() {
    var ent = {
      url: this._location.split("#")[0]
    };
    var time = +new Date();
    var _this = this;
    let url = baseUrl + "/wechat/jsApiSignature?url=" + ent.url;
    axios
      .post(url, ent, {
        headers: {
          Authorization: s.localStorage.get("token")
        }
      })
      .then(
        res => {
          console.log("success");
          _this._xhrSuccess(res.data.data);
        },
        err => {
          _this._xhrError(err);
          console.log("error");
        }
      );
  }

  _xhrSuccess(data) {
    // 成功
    this._wxConfig(data);
    if (this._debug) {
      this.showShareDebug();
    }
  }
  _xhrError(e) {
    // 失败
  }
  _wxConfig(data) {
    let _this = this;
    wx.config({
      debug: _this._debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: data.appId, // 必填，公众号的唯一标识
      timestamp: data.timestamp, // 必填，生成签名的时间戳
      nonceStr: data.nonceStr, // 必填，生成签名的随机串
      signature: data.signature, // 必填，签名，见附录1
      jsApiList: [
        "checkJsApi",
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "onMenuShareQQ",
        "onMenuShareWeibo",
        "onMenuShareQZone"
      ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    });
  }
  wxReady() {
    let _this = this;
    wx.ready(function() {
      //获取“分享给朋友”按钮点击状态及自定义分享内容接口
      wx.onMenuShareAppMessage(_this._shareConfig);
      // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
      wx.onMenuShareTimeline(_this._shareConfig);
      //获取“分享到QQ”按钮点击状态及自定义分享内容接口
      wx.onMenuShareQQ(_this._shareConfig);
      //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
      wx.onMenuShareWeibo(_this._shareConfig);
      //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
      wx.onMenuShareQZone(_this._shareConfig);
    });
  }

  wxError() {
    let _this = this;
    wx.error(function(res) {
      console.log("wxError", res);
      // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });
  }

  changeConfig(shareConfig) {
    //获取“分享给朋友”按钮点击状态及自定义分享内容接口
    wx.onMenuShareAppMessage(shareConfig);
    // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
    wx.onMenuShareTimeline(shareConfig);
    //获取“分享到QQ”按钮点击状态及自定义分享内容接口
    wx.onMenuShareQQ(shareConfig);
    //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
    wx.onMenuShareWeibo(shareConfig);
    //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
    wx.onMenuShareQZone(shareConfig);
    console.log("wxChangeConfig");
  }

  getBasePath() {
    let basePath = "",
      origin = "",
      pathName = "";
    if (origin in location) {
      origin = location.origin;
    } else {
      origin =
        location.protocol +
        "//" +
        location.hostname +
        (location.port ? ":" + location.port : "");
    }
    let pathNameList = location.pathname.split("/");
    pathNameList.pop();
    pathNameList.push("");
    pathName = pathNameList.join("/");
    basePath = origin + pathName;
    return basePath;
  }

  addImg() {
    // 添加首张图片  //仅QQ里面可以显示了
    let body = document.body;
    if (!body) {
      return;
    }
    let img = document.createElement("img");
    img.src = this._shareConfig.imgUrl;
    img.style.cssText =
      "position:absolute;top:-600%;left:0;width:320px;height:auto";
    body.insertBefore(img, body.childNodes[0]);
  }
  showShareDebug() {
    // 显示debug
    console.log(
      "%c--------------------SHARE START--------------------\n%cShare51\u63d0\u793a\n%c\u5206\u4eab\u6807\u9898\uff1a%c" +
        this._shareConfig.title +
        "\n%c\u5206\u4eab\u8be6\u60c5\uff1a%c" +
        this._shareConfig.desc +
        "\n%c\u5206\u4eab\u56fe\u7247\uff1a%c" +
        this._shareConfig.imgUrl +
        "\n%c\u5206\u4eab\u94fe\u63a5\uff1a%c" +
        this._shareConfig.link +
        "\n%c--------------------SHARE END--------------------",
      "color:#989a9d;",
      "font-size:20px;",
      "color:#000;",
      "color:green;",
      "color:#000;",
      "color:green;",
      "color:#000;",
      "color:green;",
      "color:#000;",
      "color:green;",
      "color:#989a9d;"
    );
  }
}
let install = function(Vue) {
  Vue.prototype.$share = new Share();
};

export default { install };
